package cn.edu.stu.syllabus.repository.banner;

import android.support.annotation.NonNull;

import javax.inject.Inject;

import cn.edu.stu.syllabus.repository.banner.local.BannerInfoEntry;
import cn.edu.stu.syllabus.di.scope.FragmentScoped;
import cn.edu.stu.syllabus.di.qualifier.Local;
import cn.edu.stu.syllabus.di.qualifier.Remote;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by daidaijie on 2017/3/13.
 */


@FragmentScoped
public class BannerRepository implements BannerDataSource {

    private BannerDataSource mBannerLocalDataSource;
    private BannerDataSource mBannerRemoteDataSource;

    @Inject
    public BannerRepository(@Local BannerDataSource bannerLocalDataSource,
                            @Remote BannerDataSource bannerRemoteDataSource) {
        mBannerLocalDataSource = bannerLocalDataSource;
        mBannerRemoteDataSource = bannerRemoteDataSource;
    }

    @Override
    public Observable<BannerInfoEntry> getBannerInfos() {
        return Observable.concat(mBannerLocalDataSource.getBannerInfos()
                , mBannerRemoteDataSource.getBannerInfos()
                        .doOnNext(new Action1<BannerInfoEntry>() {
                            @Override
                            public void call(BannerInfoEntry bannerInfoEntry) {
                                saveBannerInfo(bannerInfoEntry);
                            }
                        }))
                .onErrorResumeNext(new Func1<Throwable, Observable<? extends BannerInfoEntry>>() {
                    @Override
                    public Observable<? extends BannerInfoEntry> call(Throwable throwable) {
                        return mBannerLocalDataSource.getBannerInfos();
                    }
                });
    }

    public void saveBannerInfo(@NonNull BannerInfoEntry bannerInfoEntry) {
        mBannerLocalDataSource.saveBannerInfo(bannerInfoEntry);
    }
}
